<?php
/**
 * 邮寄管理
 * @Author sunge
 * @DateTime  2019-06-19
 */
namespace App\Http\Controllers\Admin;

use App\Exceptions\FormException;
use App\Http\Controllers\Controller;
use App\Models\Goods;
use App\Models\Order;
use App\Models\GlobalConfig;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
use App\Http\Controllers\LayuiController as Layui;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Validator;


class PostController extends Controller
{
    /**
     * 邮寄配置页面
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function getList()
    {
        $msg = Order::with(['orderGoods'])->orderBy('id','desc')
            ->get()->sum('postage');
        return view('Admin.post.index',compact('msg'));
    }

    /**
     * 邮寄配置页数据
     * @param Request $request
     * @return array
     */
    public function table(Request $request){
        $payload = $request->all(['keyword','time','status']);

        $preData = Order::with(['orderGoods'])->orderBy('id','desc')->where("order_type",Order::TYPE_ONLINE)
            ->when($keyword = array_get($payload,'keyword'),function($query)use($keyword){
                $query->where('user_name','like',"%$keyword%")
                ->orWhere('user_phone','like',"%$keyword%")
                ->orWhere('online_order','like',"%$keyword%")
                ->orWhere('under_order','like',"%$keyword%")
                ->orWhere('express_order','like',"%$keyword%");
            })
            ->when($status = array_get($payload,'status'),function($query)use($status){
                if($status == 1){//已发货
                    $query->whereIn('status',[Order::STATUS_WAIT_COLLECT]);
                }elseif($status == 2){//未发货
                    $query->whereIn('status',[Order::STATUS_WAIT_DELIVER]);
                }
            },function($query)use($status){
                    $query->whereIn('status',[Order::STATUS_WAIT_DELIVER,Order::STATUS_WAIT_COLLECT,Order::STATUS_SUCCESS]);
            })
            ->when($time = array_get($payload,'time'),function($query)use($time){
                $time = explode(' - ',$time);
                $time[1] = Carbon::parse($time[1])->addDay()->toDateString();
                $query->whereBetween('created_at',$time);
            })
            ->paginate($request->get('limit',10));
            $Data = $preData->map(function($item){
                $item->postage = round($item->postage,2);
                $item->express_name = array_key_exists($item->express_name,Order::EXPRESS)? Order::EXPRESS[$item->express_name] : "";
                $item->post_status = $item->status==Order::STATUS_WAIT_DELIVER ? "待邮寄":($item->status==Order::STATUS_SUCCESS ? "已签收" : "邮寄中");
                return $item;
            });
            $totalmoney = $preData->sum('postage');

        return Layui::tableJson($Data->toArray(),0,$preData->total(),$totalmoney);
    }

    /**
     * 邮寄详情页
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function detail($id)
    {
        $order = Order::with(['OrderGoods','userInfo'])->findOrFail($id);
        $goods = $order->OrderGoods;
        return view('Admin.post.detail',compact('order','goods','id'));
    }

    /**
     * 快递配置页
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function config(Request $request)
    {
        $fare = GlobalConfig::where('code','fare')->first()->value;
        $fare_condition = GlobalConfig::where('code','fare_condition')->first()->value;
        $fare_condition1 = GlobalConfig::where('code','fare_condition1')->first()->value;
        $fare_condition2 = GlobalConfig::where('code','fare_condition2')->first()->value;
        $first_weight = GlobalConfig::where('code','first_weight')->first()->value;
        $first_money = GlobalConfig::where('code','first_money')->first()->value;
        $every_up_money = GlobalConfig::where('code','every_up_money')->first()->value;

        return view('Admin.post.config',compact('fare','fare_condition1','fare_condition2','first_weight','first_money','every_up_money','fare_condition'));
    }

    /**
     * 快递配置保存
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws FormException
     */
    public function configSave(Request $request)
    {
        $load = $request->all([
            'fare_condition2'
            ,'fare_condition1'
            ,'fare_condition'
            ,'fare'
            ,'first_weight'
            ,'first_money'
            ,'every_up_money'
        ]);
         Validator::make($load, [
             'fare_condition2' =>'required|min:0',
             'fare_condition1' =>'required|min:0',
             'first_weight' =>'required|min:0',
             'first_money' =>'required|min:0',
             'every_up_money' =>'required|min:0',
         ],[
             'fare_condition2.required'  =>'请输入单次购买商品数量超出一定数量免除运费数',
             'fare_condition2.min:0'     =>'数量不能小于0',
             'fare_condition1.required'  =>'请输入单次购买金额超出一定数量免除运费',
             'fare_condition1.min:0'     =>'数量不能小于0',
             'first_weight.min:0'     =>'首重金额不能小于0',
             'first_weight.required'     =>'请输入首重金额（单位元）',
             'first_money.required'     =>'请输入首重金额（单位元）',
             'first_money.min:0'     =>'首重金额（单位元）不能小于0',
             'every_up_money.required'     =>'请输入每超出1000g金额（单位元)',
             'every_up_money.min:0'     =>'每超出1000g金额（单位元）不能小于0',
         ])->validate();
        DB::beginTransaction();
        try{
            foreach($load as $key=>$value){
                GlobalConfig::where('code', $key)->update(['value' => $value]);
            }
            if($request->input('fare')){
                GlobalConfig::where('code', 'fare')->update(['value' => \App\Models\GlobalConfig::FARE_IS]);

            }
//            else {
//                DB::update('UPDATE bb_order SET postage=0,real_pay=real_pay-postage WHERE status =1' );
//            }
        }catch (\Exception $exception){
            DB::rollBack();
            throw new FormException(App::environment('local') ? $exception->getMessage() : '保存失败' );
        }
        DB::commit();
        return $this->getResponse('保存成功');

    }


}